﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Nxg.Blog.Core.Commands;
using Nxg.Blog.Core.Commands.Accounts;
using Nxg.Blog.Web.Features;
using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Nxg.Blog.Web.Controllers
{
    public class AccountController : BaseController
    {
        private readonly ICommandInvokerFactory _commandInvoker;
        public AccountController(ICommandInvokerFactory commandInvoker)
        {
            _commandInvoker = commandInvoker;
        }

        [HttpGet]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [Route("Login")]
        public async Task<ActionResult> LoginAsync(LoginCommand command)
        {
            var commandResult = _commandInvoker.Handle<LoginCommand, LoginCommandResult>(command);
            DateTime? expiry = null;
            if (!commandResult.Success)
            {

            }
            if (command.RememberMe)
            {
                expiry = DateTime.Now.AddDays(7);
            }
            var identity = new ClaimsIdentity("AccountLogin");
            identity.AddClaim(new Claim(ClaimTypes.Name, commandResult.Author.DisplayName));
            identity.AddClaim(new Claim(ClaimTypes.Email, commandResult.Author.Email));
            identity.AddClaim(new Claim("AuthorId", commandResult.Author.Id.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Role, string.Join(",", commandResult.Author.Roles)));
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
            return Redirect(command.ReturnUrl ?? "/Home/Index");
        }

        [Route("Logout")]
        public async Task<ActionResult> LogoutAsync()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Redirect("~/Home/Index");
        }
    }
}
